import RTLog from './rt_log.js';

export default {
    checkAuthSetting(scope, open_tips) {
        return new Promise((resolve, reject) => {
            let setting = wx.getSetting({
                success: (res) => {
                    var auth = res.authSetting;
                    console.log(auth);
                    const authKey = scope;

                    if (authKey in auth && auth[authKey]) {
                        resolve();
                    } else {
                        if (authKey in auth) {
                            wx.showModal({
                                title: '提示',
                                content: open_tips,
                                success: (res) => {
                                    if (res.confirm) {
                                        wx.openSetting({
                                            success: (res) => {
                                                if (
                                                    scope in res.authSetting &&
                                                    res.authSetting[scope]
                                                ) {
                                                    resolve();
                                                } else {
                                                    reject('打开授权失败');
                                                }
                                            }
                                        });
                                    } else {
                                        reject('取消保存');
                                    }
                                },
                                fail: (err) => {
                                    reject(err);
                                }
                            }); // showModal
                        } else {
                            wx.authorize({
                                scope: authKey,
                                success() {
                                    resolve();
                                },
                                fail(err) {
                                    reject(err);
                                }
                            });
                        }
                    }
                },
                fail: (err) => {
                    RTLog.error('get setting fail! err:', err);
                    reject(err);
                }
            });
        });
    },
    saveImage(url, tips) {
        if (typeof url == 'string') {
            url = [url];
        }

        tips = tips || '图片已保存';
        return new Promise((resolve, reject) => {
            this.checkAuthSetting(
                'scope.writePhotosAlbum',
                '您现在不允许小程序访问手机相册，请打开"保存到相册"'
            ).then(
                () => {
                    (function iterator(i) {
                        if (i == url.length) {
                            wx.hideLoading();
                            wx.showToast({
                                title: tips,
                                icon: 'none',
                                duration: 1500
                            });
                            resolve();
                            return;
                        }
                        wx.showLoading({
                            title: '保存中' + (i + 1) + '/' + url.length,
                            mask: true
                        });
                        wx.downloadFile({
                            url: url[i],
                            success: function (res) {
                                wx.saveImageToPhotosAlbum({
                                    filePath: res.tempFilePath,
                                    success: function (res) {
                                        iterator(i + 1);
                                    },
                                    fail: function (err) {
                                        wx.showToast({
                                            title: '图片保存失败',
                                            icon: 'none',
                                            duration: 1500
                                        });
                                        reject(err); // 后端调用saveImage请忽略此处报错
                                    }
                                }); // wx.saveImageToPhotosAlbum
                            },
                            fail: function (err) {
                                wx.showToast({
                                    title: '图片下载失败',
                                    icon: 'none',
                                    duration: 1500
                                });
                                reject(err);
                            }
                        }); // wx.downloadFile
                    })(0);
                },
                (err) => {
                    wx.showToast({
                        title: '图片保存失败',
                        icon: 'none',
                        duration: 1500
                    });
                    reject(err);
                }
            );
        });
    },
    safeNavigateBack(opts) {
        try {
            opts = opts || {};
            cb_fail = opts.fail;
            opts.fail = (err) => {
                cb_fail && cb_fail(err);
                wx.redirectTo({
                    url: '/pages/index/index'
                });
            };

            wx.navigateBack(opts);
        } catch (err) {
            wx.redirectTo({
                url: '/pages/index/index'
            });
        }
    },
    // 错误信息优化
    errorMessageReadable(msg) {
        msg = msg || '未知错误';
        try {
            // 删除微信小程序框架底层堆栈日志
            msg = msg
                .trim()
                .split('\n')
                .filter((line) => {
                    return /.*WA\w*(Service|Context)\.js:2:/.test(line) === false;
                })
                .join('\n');

            const knownErrors = [
                {
                    reg: /.*(ERR_ADDRESS_UNREACHABLE|ERR_INTERNET_DISCONNECTED|ERR_CONNECTION_ABORTED|ERR_NAME_NOT_RESOLVED|ERR_CONNECTION_REFUSED)$/,
                    content: (msg) => {
                        return '网络错误，请检查您手机网络是否正常';
                    }
                },
                {
                    reg: /.*(请求超时|timeout)$/,
                    content: (msg) => {
                        return '请求超时，请检查您手机网络是否正常';
                    }
                },
                {
                    // navigateTo:fail page "pages/orders2/orders" is not found
                    reg: /.*:fail page \"[\w\/]+\" is not found$/,
                    content: (msg) => {
                        let page = msg.split('fail page ')[1].split(' ')[0];
                        return '页面不存在: ' + page.replace(/\"/g, '');
                    }
                }
            ];

            for (let i = 0; i < knownErrors.length; ++i) {
                if (knownErrors[i].reg.test(msg)) {
                    msg = knownErrors[i].content(msg);
                    break;
                }
            }
        } catch (e) {
            console.error(e);
        }

        return msg;
    },
    // 递归深拷贝: https://www.jianshu.com/p/9fec48213ada
    assignDeep(target, ...sources) {
        // 1. 参数校验
        if (target == null) {
            throw new TypeError('Cannot convert undefined or null to object');
        }

        // 2. 如果是基本类型数据转为包装对象
        let result = Object(target);

        // 3. 缓存已拷贝过的对象，解决引用关系丢失问题
        if (!result['__hash__']) {
            result['__hash__'] = new WeakMap();
        }
        let hash = result['__hash__'];

        sources.forEach((v) => {
            // 4. 如果是基本类型数据转为对象类型
            let source = Object(v);
            // 5. 遍历原对象属性，基本类型则值拷贝，对象类型则递归遍历
            Reflect.ownKeys(source).forEach((key) => {
                // 6. 跳过自有的不可枚举的属性
                if (!Object.getOwnPropertyDescriptor(source, key).enumerable) {
                    return;
                }
                if (typeof source[key] === 'object' && source[key] !== null) {
                    // 7. 属性的冲突处理和拷贝处理
                    let isPropertyDone = false;
                    if (
                        !result[key] ||
                        !(typeof result[key] === 'object') ||
                        Array.isArray(result[key]) !== Array.isArray(source[key])
                    ) {
                        // 当 target 没有该属性，或者属性类型和 source 不一致时，直接整个覆盖
                        if (hash.get(source[key])) {
                            result[key] = hash.get(source[key]);
                            isPropertyDone = true;
                        } else {
                            result[key] = Array.isArray(source[key]) ? [] : {};
                            hash.set(source[key], result[key]);
                        }
                    }
                    if (!isPropertyDone) {
                        result[key]['__hash__'] = hash;
                        this.assignDeep(result[key], source[key]);
                    }
                } else {
                    Object.assign(result, { [key]: source[key] });
                }
            });
        });

        delete result['__hash__'];
        return result;
    },
    // 格式化url
    formatUrl(url) {
        let formatUrl = '';
        if (!url) return '';
        if (url.startsWith('https') || url.startsWith('http')) {
            formatUrl = url;
        } else {
            formatUrl = `https://mp.weixin.qq.com/s/${url}`;
        }
        return formatUrl;
    },
    getUrlParams(url) {
        const str = url.substr(url.indexOf('?') + 1)
        const arr = str.split('&')
        const result = {}
        for (let i = 0; i < arr.length; i++) {
            const item = arr[i].split('=')
            result[item[0]] = item[1]
        }
        return result;
    },
    _showErrorReturn(msg) {
        wx.showModal({
            title: '错误提示',
            content: msg,
            showCancel: false,
            success: () => {
                safeNavigateBack();
            }
        });
    }
};
